<?php

namespace app\index\controller;

use think\Db;
use think\Request;

class User
{
    // 入口
    public function index()
    {
        return ['data' => '欢迎来到api.vchao.top', 'code' => 1, 'message' => '操作完成'];
    }

    // 登录
    public function login()
    {
        $request = Request::instance();
        $username = $request->param('username');
        $password = $request->param('password');

        $res = Db::table('user')
            ->where('user_name', '=', $username)
            ->where('password', '=', $password)
            ->find();
        if ($res) {
            return ['code' => 1, 'message' => 'success', 'data' => $res];
        } else {
            return ['code' => 2, 'message' => 'fail', 'data' => $res];
        }
    }

    // 停用用户
    public function stopUser()
    {
        $request = Request::instance();
        $user_id = $request->param('user_id');

        $res = Db::table('user')
            ->where('user_id', '=', $user_id)
            ->update(['user_state' => '0']);

        if ($res) {
            return ['code' => 1, 'message' => 'success'];
        } else {
            return ['code' => 2, 'message' => 'fail'];
        }
    }

    // 启用用户
    public function startUser()
    {
        $request = Request::instance();
        $user_id = $request->param('user_id');

        $res = Db::table('user')
            ->where('user_id', '=', $user_id)
            ->update(['user_state' => '1']);

        if ($res) {
            return ['code' => 1, 'message' => 'success'];
        } else {
            return ['code' => 2, 'message' => 'fail'];
        }
    }

    // 新增用户
    public function insert()
    {
        $request = Request::instance();
        $username = $request->param('username');
        $password = $request->param('password');

        $data = ['user_name' => $username, 'password' => $password];
        $res = Db::table('record')->insert($data);

        if ($res) {
            return ['code' => 1, 'message' => 'success'];
        } else {
            return ['code' => 2, 'message' => 'fail'];
        }
    }
}
